import numpy as np

def conv2D(img, kernel):
    # 获取图像和卷积核的维度
    img_height, img_width = img.shape
    kernel_height, kernel_width = kernel.shape
    # 计算输出图像的维度
    output_height = img_height - kernel_height + 1
    output_width = img_width - kernel_width + 1
    # 初始化输出图像
    output = np.zeros((output_height, output_width))
    # 进行卷积操作
    for i in range(output_height):
        for j in range(output_width):
            # 提取当前窗口
            window = img[i:i+kernel_height, j:j+kernel_width]
            # 计算卷积
            output[i, j] = np.sum(window * kernel)
    
    return output

img = np.array([[3,0,2,1,0,0],
                [2,0,1,2,3,0],
                [0,1,0,0,3,1],
                [2,1,0,3,2,0],
                [2,0,2,0,1,2]], dtype=np.float32)

print(f"原数组:\n{img}")

kernel = np.array([[1,0,1],
                   [0,4,0],
                   [1,0,1]])

convolved_img = conv2D(img, kernel)
print(f"valid卷积:\n{convolved_img}")
padded_arr = np.pad(img, pad_width=1, mode='constant', constant_values=0)
convolved_pdimg = conv2D(padded_arr, kernel)
print(f"same卷积:\n{convolved_pdimg}")
